<template>
    <div>
        <el-row :gutter="20" >
            <el-col :span="16" class="paddCol"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.6)">
                <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span><i class="el-icon-menu"></i> 电子地图</span>
                </div>
                <!-- 电子地图 -->
                <div class="map">
                    <img :src="mapImg" alt="">
                    <div class="jiedian">
                       <span v-for="item in moveArr" :key="item.index">
                            <button :class="item.id == activeId ? 'move active' : 'move '" @mousedown="move" :id="item.id" :style="{left:item.positionY, top:item.positionX, color:item.color, fontSize:item.size}">
                                {{item.value}}
                            </button>
                       </span>
                        
                    </div>
                </div>
                </el-card>
            </el-col>
             <el-col :span="8" class="paddCol">
                <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span><i class="el-icon-menu"></i> 地图配置</span>
                </div>
                <div class="upload">
                    <a href="javascript:;" class="file">上传电子地图
                        <input type="file" ref="fileBtn" @change="uploadImg" />
                    </a>
                    <!-- <a href="javascript:;" class="file">上传电子地图文件
                        <input type="file" ref="file" @change="uploadImg2" />
                    </a> -->
                    <el-button type="primary" class="add" @click="add">添加设备节点</el-button>
                    <p style="margin-top: 10px;color: #e6a23c;font-size: 12px;">*电子地图文件大小不可超过1.5M, 图片长宽比例为9:4</p>
                </div>
                </el-card>
                <el-card class="box-card" style="margin-top:10px;">
                    <div slot="header" class="clearfix">
                        <span><i class="el-icon-menu"></i> 设备配置</span>
                    </div>
                    <div class="shebeiList">
                        <ul>
                            <li  v-for="(item, index) in moveArr" :key="item.index" @click="edit(item.id, index)" :class='{ active:index===number}'>
                                {{item.value}}
                            </li>
                        </ul>
                    </div>
                    <div class="shebeiDetails">
                        <!-- <span>x轴坐标：{{this.positionX}} &nbsp;&nbsp;&nbsp;y轴坐标：{{this.positionY}}</span> -->
                        <div class="block" style="margin-top:10px;">
                            设备绑定:&nbsp;&nbsp;<el-button type="primary" size="small" @click="dialogVisible = true">设备绑定</el-button>
                        </div>  
                        <div class="block">
                            文字颜色:&nbsp;&nbsp;<el-color-picker v-model="textcolor"  size="small"></el-color-picker>
                        </div>    
                        <div class="block" style="margin-top:10px;">
                            字体大小:&nbsp;&nbsp;
                            <el-radio v-model="textSize" label="22">大</el-radio>
                            <el-radio v-model="textSize" label="18">中</el-radio>
                            <el-radio v-model="textSize" label="14">小</el-radio>
                        </div>    
                        <div style="text-align:right;">
                                <el-button type="danger" size="small"   @click="delJiedian()" style="width:120px;">删除</el-button>
                                <el-button type="primary" size="small"   @click="saveSet()" style="width:120px;">暂存</el-button>
                        </div>
                    </div>
                </el-card>
                <el-button type="primary"  @click="saveAllSet()" style="width:120px; float:right;margin-top:20px;margin-left:20px;background: rgba(89, 129, 165, 0.8);border:none;">保存所有更改</el-button>

                <el-button type="primary"  @click="getAllSet()" style="width:120px; float:right;margin-top:20px;background: rgba(89, 129, 165, 0.8);border:none;">重置所有更改</el-button>

                
            </el-col>
        </el-row>
        <el-dialog
            title="设备绑定"
            :visible.sync="dialogVisible"
            width="60%"
            :append-to-body="true">
            <div class="baojing_title">
              <h3 style="color:#fff;margin-bottom:10px;">选择设备</h3>
            <el-input type="text" placeholder="输入绑定报警项名称" v-model="warnName" style="width:500px;" maxlength='10'></el-input>
            </div>
            <div class="shebeiBox">
                <h3 style="color:#fff;">选择设备</h3>
                <!-- <span v-for="(item,index) in this.sidemenu" :key="index">
                    <el-radio v-model="radio1" :label="item.type"  border @change="checkChild($event)">{{item.typename}}</el-radio>
                </span> -->
                <div class="warnhis_type_flex" >
                    <div class="warnhis_type_but" v-for="(item,index) in this.sidemenu" :key="index" @click="selectType(item)">
                        <div :class="item.active == 1 ? 'warnhis_type_active':'warnhis_type_nomal'">
                            {{item.typename}}
                        </div>
                    </div>
                </div>
            </div>
             <div class="shebeiBox" style="margin-top:30px;">
                 <h3 style="color:#fff;" v-if="this.childData !== ''">选择子设备</h3>
                <!-- <span v-for="item in childData" :key="item.index">
                    <el-radio v-model="radio2" :label="item.name" @change="typeseiral(item.index, item.type)"  border>{{item.name}}</el-radio>
                </span> -->
                <div class="warnhis_type_flex">
                    <div class="warnhis_type_but" v-for="(item,index) in this.childData" :key="index" @click="selectTypelink(item)">
                        <div :class="item.active == 1 ? 'warnhis_type_active':'warnhis_type_nomal'">
                            {{item.name}}
                        </div>
                    </div>
                </div>
            </div>
             <div class="shebeiBox shebeiBox3" style="margin-top:30px;">
                 <h3 style="color:#fff;">选择设备报警项</h3>
                <!-- <span v-for="item in leafChildData" :key="item.index">
                    <el-radio v-model="radio3" :label="item.name" @change="leafChild(item.id)" v-if="item.activity == 1" border>{{item.name}}</el-radio>
                </span> -->
                <div class="warnhis_shebei">
                    <div class="warnhis_type_flex">
                        <div class="warnhis_type_but" v-for="(item,index) in this.leafChildData.unit" :key="index" @click="selectTypedata(item)">
                            <div :class="item.active == 1 ? 'warnhis_type_active':'warnhis_type_nomal'">
                                {{item.name}}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveBind()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
        
</template>

<script>
// import { delete } from 'vue/types/umd'
export default {
    data () {
        return{
            timeSysData:'',//接口方法的定时器
            labelPosition: 'right',
	        imgInfo: null,
            imgSrc: null,
            base:'',
            loading: false,
            mapImg: '',
            positionX: '',
            positionY: '' ,
            moveArr:[],
            arry: [],
            activeId: 0,
            number: 0,
            dialogVisible: false, //设备选择 
            radio2:'',
            radio3:'',
            textcolor:'#409EFF',
            textSize: '18',
            sidemenu : [],
            childData: [],
            nowChildType:'',
            nowChildUid:'',
            nowChildAddr:'',
            nowLeafSerial: '',
            leafChildData:'',
            warnName:''
        }
    },
    created() {
        if(localStorage.getItem('map') == '' || localStorage.getItem('map') == '{}' || localStorage.getItem('map') == null){
            this.mapImg = require('../../assets/map.png')
        } else{
            this.mapImg = localStorage.getItem('map')
        }
        this.moveArr =  JSON.parse(localStorage.getItem('moveArr')) 
        this.getlist();
        this.getlayout9();
    },
    
    methods: {
        // 电子地图文件上传
        // uploadImg2() {
        //   const fileInput = this.$refs.file;
        //   const file = fileInput.files[0]
        //   const formData = new FormData();
        //   formData.append('file', file);

        //   this.$http.post(this.$baseUrl, formData, {
        //     headers: {
        //       'Content-Type': 'multipart/form-data'
        //     },
        //     onUploadProgress: e => {
        //       // 上传进度的处理逻辑
        //     }
        //   }).then(res => {
        //     // 上传成功的处理逻辑
        //   }).catch(err => {
        //     // 异常处理逻辑
        //   })
        // },
        // 电子地图选择
        uploadImg() {
    			var that = this;
    			const inputFile = this.$refs.fileBtn.files[0];
    			let res;
    			console.log('选了图片');
                console.log(inputFile);
                this.loading = true
    			this.inputFile = inputFile;
    			if (this.inputFile) {
    				let inputFile = this.inputFile;
    				if (inputFile.type !== 'image/png') {
                        this.$notify({
                            title: '请选择png格式文件',
                            type: 'warning',
                            duration: 2000
                        });
                        this.loading = false
    					return;
    				}
    				this.imgInfo = Object.assign({}, this.imgInfo, {
    					name: inputFile.name,
    					size: inputFile.size,
    					lastModifiedDate: inputFile.lastModifiedDate.toLocaleString()
    				});
    				const reader = new FileReader();
    				res = reader.readAsDataURL(this.inputFile);
    				reader.onloadend = function() {
                        this.base =  reader.result.substring(0);
                        localStorage.setItem("map", this.base)
    				};
    				reader.onload = function(e) {
    					console.log(e);
    					that.imgSrc = this.result;   // 注意:这里的this.result中,这个this不是vue实例,而是reader对象,所以之前用that接收vue示例  that.imgSrc   
                    };
                    setTimeout(() =>{
                        this.getlayout6()
                        
                    },2000);

                     
    			} else {
    				return;
    			}
        },
        //电子地图上传
        getlayout6(){
            var params = {
                "setlayout":"layout6",
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token"),
                "layout":localStorage.getItem('map')
                
            }
            console.log(params)    
            this.$http.post(this.$baseUrl, params).then((res) => {
                console.log(res) 
                if(res.data.result !== 'ok'){
                    this.mapImg = require('../../assets/map.png')
                    localStorage.setItem("map", '{}')
                    this.$notify({
                        title: '上传失败',
                        type: 'warning',
                        duration: 1500
                    });
                }else{
                    this.mapImg = localStorage.getItem('map')
                }
                this.loading = false
            });
        },
        //电子地图节点获取
        getlayout9(){
            var ss = 0
            var params = {
                "getlayout":"layout9",
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                if(res.data.result == 'ok'){
                    if(res.data.layout9 == undefined){
                        ss++
                    }else{
                    }
                }else if(res.data.result =='No access rights.'){
                }
                
            });
            if(ss > 0){ //有返回并且接口失败  重新获取
                // 停止循环接口
                clearInterval(this.timeSysData);
                this.timeSysData = null;
                this.$nextTick(() => {
                    this.timeSysData = setInterval(() => {
                        this.getlayout9()
                    }, 3000); 
                })
            }else{
                // 停止循环接口
                clearInterval(this.timeSysData);
                this.timeSysData = null;
            }
        },
        // 设备节点拖动
        move(e) {
            console.log(e.target.classList)
            if(e.target.classList[1] == 'active') {
                let odiv = e.target;
            let disX = e.clientX - odiv.offsetLeft;
            let disY = e.clientY - odiv.offsetTop;
            document.onmousemove = (e) => {
                let left = e.clientX - disX;
                let top = e.clientY - disY;
                
                // 绑定元素到positionX positionY
                this.positionX = top;
                this.positionY = left;
                this.moveArr[e.target.id].positionX =  this.positionX + 'px';
                this.moveArr[e.target.id].positionY =  this.positionY + 'px'
                localStorage.setItem("moveArr",  JSON.stringify( this.moveArr))
                // 移动元素
                odiv.style.left = left + 'px';
                odiv.style.top = top + 'px';
                if (top < 0) {
                    odiv.style.top = 0 + 'px';

                } if(top > 400) {
                    odiv.style.top = 400 + 'px';

                } if( left < 0) {
                     odiv.style.left = 0 + 'px';

                } if (left >900) {
                     odiv.style.left = 900 + 'px';
                    
                } if(top < 0 && left < 0) {
                    odiv.style.left = 0 + 'px';
                    odiv.style.top = 0 + 'px';
                }
               
            }
            document.onmouseup = (e) => {                
                document.onmousemove = null;
                document.onmouseup = null;
                 // 放入数组中存贮
                 var arr = []
                 if( this.positionX < 0) {
                    this.positionX = 0 
                 }  if(this.positionX > 400) {
                    this.positionX = 400 
                 }  if(this.positionY < 0) {
                    this.positionY = 0
                 }  if(this.positionY > 900) {
                    this.positionY = 900
                 } 
                console.log(e.target.id)
                this.moveArr[e.target.id].positionX =  this.positionX + 'px';
                this.moveArr[e.target.id].positionY =  this.positionY + 'px'
                localStorage.setItem("moveArr",  JSON.stringify( this.moveArr))
                return false;
            }  
            } else {
                return
            }
            
        },                      
        
        // 添加设备
        add() {
            let ss = Object.assign(this.arry, this.moveArr, {})
            console.log(ss)
            var obj = {
                'el': 'move',
                'id': this.arry.length,
                'positionX': 0,
                'positionY': 0,
                'value':'设备',
                'size':'',
                'color':'',
                'type':'',
                'uid':'',
                'addr':'',
                'warning':'',
                's_id':''


            }
            ss.push(obj)
            console.log(this.arry)
            this.moveArr = ss;
        },
        
        // 编辑设备
        edit(e, index) {
            // console.log(index)
            this.activeId = index
            this.number= index;  

        },

        // 获取设备列表
        getlist(){
            var params = {
                "getdevlink":"",
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                this.sidemenu = []
                if(res.data.result == 'ok'){
                    var data = res.data.getdevlink
                    for(var i = 0; i < data.length; i++){
                        var s = 0
                        if(data[i].type != 31 && data[i].type != 32){//屏蔽掉31 32无线网关模块设备
                            for(var y = 0; y < data[i].devlink.length; y++){
                                if(data[i].devlink[y].ready == 1){
                                    s++
                                }
                            }
                            if(s > 0){
                                var arr = {
                                    devlink:data[i].devlink,
                                    type:data[i].type,
                                    typename:data[i].typename,
                                    active:0
                                }
                                this.sidemenu.push(arr)
                            }
                        }
                        
                    }
                }
            })
        },
        // 一级菜单绑定
        // 获取已开启的具体设备 
        // 点击设备类型
        selectType(data){
            for(var a = 0;  a < this.sidemenu.length; a++){
                if(this.sidemenu[a].type == data.type){
                    this.sidemenu[a].active = 1
                }else{
                    this.sidemenu[a].active = 0
                }
            }
            this.childData = []
            this.leafChildData = {}
            this.radio2 = ''
            
            for(var i = 0; i < data.devlink.length; i++){
                if(data.devlink[i].ready == 1){
                    var arr = {
                        type:data.type,
                        addr:data.devlink[i].addr,
                        uid:data.devlink[i].uid,
                        typename:data.typename,
                        name:data.devlink[i].name,
                        active:0
                    }
                    this.childData.push(arr)
                }
            }
        },
        // 二级菜单绑定
        // 点击具体设备
        selectTypelink(data){
            for(var a = 0;  a < this.childData.length; a++){
                if(this.childData[a].uid == data.uid && this.childData[a].addr == data.addr && this.childData[a].type == data.type){
                    this.childData[a].active = 1
                    this.radio2 = this.childData[a]
                }else{
                    this.childData[a].active = 0
                }
            }
            this.leafChildData = {}
            var params = {
                "getdevinfo":[{
                    "uid":data.uid,
                    "type":data.type,
                    "addr":data.addr,
                    "unittype":"id-name-ready"
                }],
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                if(res.data.result == 'ok'){
                    var srt = []
                    for(var i = 0; i < res.data.getdevinfo[0].unit.length; i++){
                        var ssd = {
                            ready:res.data.getdevinfo[0].unit[i].ready,
                            id:res.data.getdevinfo[0].unit[i].id,
                            name:res.data.getdevinfo[0].unit[i].name,
                            active:0
                        }
                        if(res.data.getdevinfo[0].unit[i].ready == 1){
                            srt.push(ssd)
                        }
                    }
                    this.nowChildType = data.type //选择设备类型
                    this.nowChildUid = data.uid//选择设备uid
                    this.nowChildAddr = data.addr//选择设备地址
                    var arr = {
                        type:data.type,
                        addr:data.addr,
                        uid:data.uid,
                        typename:data.typename,
                        name:data.name,
                        unit:srt
                    }
                    this.leafChildData = arr
                }
            })
        },
        // 三级菜单绑定
        selectTypedata(val) {
            for(var i = 0; i < this.leafChildData.unit.length; i++){
                if(val.id == this.leafChildData.unit[i].id){
                    this.leafChildData.unit[i].active = 1
                }else{
                    this.leafChildData.unit[i].active = 0
                }
            }
            this.nowLeafSerial = val.id //选择子项id
        },
        //保存绑定设备 --弹出框关闭时按钮
        saveBind () {
            if(this.radio2 == '') {
                this.$notify({
                    title: '请绑定子设备',
                    type: 'warning',
                    duration: 2000
                });
            } else if(this.warnName == ''){
                this.$notify({
                    title: '绑定报警名称不可为空',
                    type: 'warning',
                    duration: 2000
                });
            } else {
                this.dialogVisible =  false;
                this.moveArr[this.activeId].uid = this.nowChildUid;
                this.moveArr[this.activeId].addr = this.nowChildAddr;
                this.moveArr[this.activeId].type = this.nowChildType;
                this.moveArr[this.activeId].s_id = this.nowLeafSerial;
                this.moveArr[this.activeId].value = this.warnName
                localStorage.setItem("moveArr",  JSON.stringify( this.moveArr))
                console.log(this.moveArr)
                this.warnName = ''
                this.childData = ''
                this.leafChildData = ''
                this.nowLeafSerial = ''
                this.radio2 = ''

            }
        },
        // 保存配置项设置
        saveSet () {
            this.moveArr[this.activeId].size = this.textSize + 'px';
            this.moveArr[this.activeId].color = this.textcolor;
            for (let k = 0; k < this.moveArr.length; k++) {
                // const element = array[k];
                this.moveArr[k].id = k
                
            }
            localStorage.setItem("moveArr",  JSON.stringify( this.moveArr))
            this.$notify({
                title: '保存成功',
                type: 'success',
                duration: 1500
            });
        },
        delJiedian() {
            this.moveArr.splice([this.activeId],1);
            localStorage.setItem("moveArr",  JSON.stringify( this.moveArr))
        },

        // 数据下发 保存所有数据、
        saveAllSet () {
            var params = {
                "setlayout":"layout9",
                "layout":localStorage.getItem("moveArr"),
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                   if(res.data.result !== 'ok'){
                    }else{
                        this.$notify({
                            title: '保存成功',
                            type: 'success',
                            duration: 1500
                        });
                    }
            });
        },
        //重置
        getAllSet(){
            var params = {
                "getlayout":"layout9",
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                   if(res.data.result !== 'ok'){
                    }else{
                        this.moveArr = JSON.parse(res.data.layout9);
                    }
            });
        }
    },
    beforeDestroy() {
        // 停止循环接口
        clearInterval(this.timeSysData);
        this.timeSysData = null;
    }
}
</script>

<style scoped>
   .el-card {
    background: none;
    color: #fff;
    border: 1px solid rgba(89, 129, 165, 0.4);
    }
    /deep/ .el-card__header {
    background: rgba(89, 129, 165, 0.2);

    border-bottom: none;
    }
    .box-card {
    /* overflow: hidden; */
    }
    .card_padding_chart{
    padding: 7px 0;
    }
    .map{
        text-align: center;
        position: relative;
        width: 900px;
        height: 400px;
        border: red;
        margin: 0 auto;

    }
    .map img{
        width: 900px;
        height: 400px;
    }
    .upload{
        position:relative;
    }
    .file {
    /* position: relative; */
    display: inline-block;
    background: rgba(89, 129, 165, 0.6);
    border: 1px solid rgba(89, 129, 165, 0.6);
    border-radius: 4px;
    padding: 6px 20px;
    overflow: hidden;
    color: #fff;
    text-decoration: none;
    text-indent: 0;
    line-height: 28px;
} 
.add{
    position: absolute;
    left: 200px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    color: #fff;
    text-decoration: none;
}
.jiedian{
    /* border: 1px solid rgba(89, 129, 165, 0.4); */
    position: absolute;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}
.move{
    position: absolute;
    top: 10px;
    left: 10px;
    height: 50px;
    background:  rgba(89, 129, 165, .2);
    line-height: 46px;
    min-width: 120px;
    width: auto;
    outline: none;
    border: none;
    box-shadow: none;
}
.move.active {
    border: 1px dashed #fff;
}
.move:hover{
    cursor: move;
}
.shebeiList ul li{
    display: inline-block;
    /* width: 105px; */
    padding: 0px 15px;
    line-height: 36px;
    background: rgba(89, 129, 165, 0.4);
    text-align: center;
    margin: 5px;
    border-radius: 4px;
}
.shebeiList ul li:hover{
    cursor: pointer;
}
.shebeiList ul li.active{
    border: 1px solid #fff;

}
.shebeiDetails{
    border-top:1px solid rgba(89, 129, 165, 0.4);
    margin: 15px 0;
    padding: 10px 0;
    display: grid;

}
.shebeiDetails .block{
    margin-bottom: 20px;
}
/deep/ .el-color-picker__trigger{
    top: 10px !important;
}
.shebeiDetails .el-input{
    width: 200px;
}
/deep/ .shebeiDetails .el-form-item__label{
    width: 80px;
    color: #fff;
}
/deep/ .el-dialog__title{
    color: #fff;
}
/* /deep/ .el-dialog__headerbtn .el-dialog__close{
    color: #fff;
} */
/deep/ .el-radio.is-bordered{
    color: #fff;
    margin: 10px;
}
/deep/ .shebeiBox3 .el-radio.is-bordered{
    width: auto;
}
/deep/ .el-radio{
    color: #fff;
}
.baojing_title{
    margin-bottom: 15px;
}
/deep/ .el-input__inner {
    background: none;
    outline: none;
    height: 40px;
    line-height: 40px;
    border: 1px solid #ececec;
    border-radius: 4px;
    color: #fff;
    font-size: 16px;
    font-weight: 400;
    text-indent: 10px;
    margin-right: 15px;
    width: 500px;
    padding: 0px;
}
.warnhis_type_flex{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.warnhis_type_but{
    margin-right: 20px;
    margin-top: 20px;
    border: 1px solid #ffffff8a;
    border-radius: 5px;
    cursor: pointer;
}
.warnhis_type_nomal{
    height: 50px;
    line-height: 50px;
    padding: 0px 15px;
    background: #36363614;
    color: #fff;
}
.warnhis_type_active{
    height: 50px;
    line-height: 50px;
    padding: 0px 15px;
    background: #b8e2ff29;
    color: #fff;
}
.warnhis_shebei{
    width: 100%;
    max-height: 300px;
    color: #fff;
    overflow-y: scroll;
}
</style>